//
//  CustomPresentationController.swift
//  SwiftCode
//
//  Created by yuhus on 2024/8/20.
//

import UIKit

class CustomPresentationController: UIPresentationController {
  var initialPresentationFrame: CGRect = .zero
  
  override var shouldRemovePresentersView: Bool {
    return false
  }
  
  override func presentationTransitionWillBegin() {
    guard let containerView else { return }
    containerView.addGestureRecognizer(panGestureRecognizer)
  }
  
  private lazy var panGestureRecognizer: UIPanGestureRecognizer = {
    return UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
  }()
  
  @objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
    switch gesture.state {
    case .changed:
      // 当拖动时更新presented view的状态
      let translation = gesture.translation(in: presentedView?.superview)
      let y = translation.y + initialPresentationFrame.minY
      presentedView?.frame.origin.y = y
    case .ended:
      // 当拖动结束时，根据滑动距离决定是否dismiss
      let velocity = gesture.velocity(in: presentedView?.superview)
      let translation = gesture.translation(in: presentedView?.superview)
      Timber.i(velocity)
      Timber.i("minY", presentedView!.frame.minY)
      Timber.i("translation", translation.y)
      
      if velocity.y > 300 {
        // 向上滑动并且速度足够快才dismiss
        presentingViewController.dismiss(animated: true)
      } else if translation.y > initialPresentationFrame.height / 5 {
        // 向下滑动并且超过屏幕一半才dismiss
        presentingViewController.dismiss(animated: true)
      } else {
        // 否则恢复到初始位置
        UIView.animate(withDuration: 0.25) {
          self.presentedView?.frame = self.initialPresentationFrame
        }
      }
    default:
      break
    }
  }
  
  override func containerViewWillLayoutSubviews() {
    super.containerViewWillLayoutSubviews()
    
    let with = UIScreen.main.bounds.size.width
    let height = UIScreen.main.bounds.size.height
    
    presentedView?.frame = .init(x: 0, y: height / 2, width: with, height: height)
    initialPresentationFrame = presentedView?.frame ?? .zero
    Timber.i(initialPresentationFrame)
  }
}

extension UIViewController {
  func present(_ viewControllerToPresent: UIViewController, draggable: Bool) {
    if draggable {
      viewControllerToPresent.transitioningDelegate = self
    }
    present(viewControllerToPresent, animated: true)
  }
}

extension UIViewController: UIViewControllerTransitioningDelegate {
  public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
    return CustomPresentationController(presentedViewController: presented, presenting: presenting)
  }
}
